package com.mico.echart.monitor.controller;

import com.mico.echart.monitor.config.GlobalObject;
import com.mico.echart.monitor.model.Processes;
import com.mico.echart.monitor.model.Threads;
import com.mico.echart.monitor.system.SystemInfo;
import com.mico.echart.monitor.system.SystemInfoTest;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author micocube
 * projectName: springboot-example
 * packageName: com.mico.echart.monitor.controller
 * email: ldscube@gmail.com
 * createTime: 2020-01-06 15:27
 * version: 0.1
 * description:
 */
@RestController
public class ThreadController {

    @RequestMapping("/Thread")
    public void getAllTread(HttpServletResponse response) throws IOException {

        Threads.initThreadStack();
        PrintWriter writer = response.getWriter();
        Collection<Threads> values = Threads.threadsMap.values();
        List<Threads> collect = values.stream().sorted(Comparator.comparingDouble(v -> {
            Threads value = (Threads) v;
            return Double.valueOf(value.sysCpuPercent);
        }).reversed()).collect(Collectors.toList());
        writer.println(GlobalObject.writeValueAsString(collect, true));
        writer.flush();
        writer.close();

    }


    @RequestMapping("/Process")
    public void getAllProcess(HttpServletResponse response) throws IOException {
        List<Processes> process = SystemInfo.getProcess();
        PrintWriter writer = response.getWriter();
        writer.println(GlobalObject.writeValueAsString(process, true));
        writer.flush();
        writer.close();
    }


    @RequestMapping("/Hardware")
    public void getHardware(HttpServletResponse response) throws IOException {
        SystemInfoTest.collect();
        List<String> oshi = SystemInfoTest.oshi;
        PrintWriter writer = response.getWriter();
        String value = GlobalObject.writeValueAsString(oshi, true);
        String replace = value.replaceAll("\n", "<br/>");
        writer.println(replace);
        writer.flush();
        writer.close();
    }


}
